package com.rt.easyjava.base.modules.timerjob.config;

import com.rt.easyjava.base.modules.timerjob.dto.TmptTimerBizDto;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class QuartzManager {

    @Autowired
    SchedulerConfig schedulerConfig;

    /**
     * @Description: 添加一个定时任务
     *
     * @param jobName 任务名
     * @param jobGroupName  任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass  任务
     * @param cron   时间设置，参考quartz说明文档
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void addJob(TmptTimerBizDto tmptTimerBizDto, String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cron) {
        try {
            // 任务名，任务组，任务执行类
            Scheduler scheduler = schedulerConfig.scheduler();

            //定义一个TriggerKey
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            if (trigger == null) {
                JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
                jobDetail.getJobDataMap().put("tmptTimerBizDto", tmptTimerBizDto);

                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 调度容器设置JobDetail和Trigger
                scheduler.scheduleJob(jobDetail, trigger);

                // 启动
                if (!scheduler.isShutdown()) {
                    scheduler.start();
                }
            } else {
                // Trigger已存在，那么更新相应的定时设置
                log.info("Trigger已存在，那么更新相应的定时设置:{},{}",trigger.getKey(), trigger.getCronExpression());
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 ：修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param cron   时间设置，参考quartz说明文档
     */
    /*public void modifyJobTime(String jobName,String jobGroupName, String triggerName, String triggerGroupName, String cron) {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                System.out.println("任务："+jobName+"被修改");
                *//** 方式一 ：调用 rescheduleJob 开始 *//*
               *//* // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 ：修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);*//*
                *//** 方式一 ：调用 rescheduleJob 结束 *//*

                *//** 方式二：先删除，然后在创建一个新的Job  *//*
                JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                Class<? extends Job> jobClass = jobDetail.getJobClass();
                removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass,cron);
                *//** 方式二 ：先删除，然后在创建一个新的Job *//*
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/

    /**
     * @Description: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Job状态
     * @param jobName
     * @param jobGroup
     * @return
     */
    public String getJobState(String jobName, String jobGroup){
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);
            return scheduler.getTriggerState(triggerKey).name();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //暂停所有任务
    public void pauseAllJob() {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            scheduler.pauseAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //暂停任务
    public String pauseJob(String jobName, String jobGroup) {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return "fail";
            }else {
                scheduler.pauseJob(jobKey);
                return "success";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //恢复所有任务
    public void resumeAllJob() {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            scheduler.resumeAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 恢复某个任务
    public String resumeJob(String jobName, String jobGroup) {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return "fail";
            }else {
                scheduler.resumeJob(jobKey);
                return "success";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:启动所有定时任务
     */
    /*public void startJobs() {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/

    /**
     * @Description:关闭所有定时任务
     * 关掉了，就启不起了，危险
     */
    /*public void shutdownJobs() {
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/

    /**
     * 获取当前正在执行的任务
     * @return
     */
    public boolean getCurrentJobs(String name){
        try {
            Scheduler scheduler = schedulerConfig.scheduler();
            List<JobExecutionContext> jobContexts = scheduler.getCurrentlyExecutingJobs();
            for (JobExecutionContext context : jobContexts) {
                if (name.equals(context.getTrigger().getJobKey().getName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }


}
